/**
 * 尊敬的用户，你好：页面 JS 面板是高阶用法，一般不建议普通用户使用，如需使用，请确定你具备研发背景，能够自我排查问题。
 * 我们可以用 JS 面板来开发一些定制度高功能，比如：调用API接口，自定义动作执行等等。
 */

export function didMount() {
    console.log("「页面 JS」：当前页面地址 " + location.href);
    const self = this;

    // 页面配置映射
    const PAGE_CONFIG = {
        register: { id: "1954815569568989184", title: "摊主注册" },
        pending: { id: "1958812229605969920", title: "待审核" },
        reject: { id: "1958812274166255616", title: "审核不通过" },
        info: { id: "1955078906873643008", title: "摊主信息" },
        book: { id: "1955554951754153984", title: "摊位预约" },
        mybook: { id: "1955802345355870208", title: "我的预约" }
    };


    const BUTTON_ACTIONS = {
        "btn-info": { pass: PAGE_CONFIG.info },
        "btn-book": { pass: PAGE_CONFIG.book },
        "btn-mybook": { pass: PAGE_CONFIG.mybook },
        "btn-punch": { pass: PAGE_CONFIG.info }
    };

    Object.keys(BUTTON_ACTIONS).forEach(btnId => {
        const { pass } = BUTTON_ACTIONS[btnId];
        const btn = document.getElementById(btnId);
        if (!btn) return;

        btn.addEventListener("click", () => {
            handleAction(self, pass);
        });
    });

    /**
     * 点击操作处理
     * @param self 上下文
     * @param passPage 审核通过时跳转页面
     */
    function handleAction(self, passPage) {
        let holderId = self.$$("text_input_b2dvy8").cValue;
        let weChatCode = window.WECHATVALUE;
        if (holderId) {
            getStallApprovalStatus(holderId).then(res => {
                // 状态映射
                const statusMap = {
                    "0": PAGE_CONFIG.pending,
                    "1": passPage,
                    "-1": PAGE_CONFIG.reject,
                    "-2": PAGE_CONFIG.reject
                };
                const targetPage = statusMap[res] || PAGE_CONFIG.reject;
                openPage(self, targetPage.id, targetPage.title, holderId);
            });
        } else {
            openPage(self, PAGE_CONFIG.register.id, PAGE_CONFIG.register.title, weChatCode);
        }
    }
}

/**
 * 获取当前摊主的审核状态
 * @param holderId
 */
function getStallApprovalStatus(holderId) {
    return api
        .EXEC_FORMULA(
            `ENTITY_SELECT_ONE('ds_tbl:t_1aef92529dae4723ba36422faba4e546',verify_state_id,QUERY_AND(QUERY_EQ(object_id,'${holderId}'),QUERY_EQ(apply_type_id,'3')))`
        )
        .then(response => response.result);
}

/**
 * 打开页面
 */
function openPage(self, pageId, title, params) {
    self.$router.push({
        name: "page-preview",
        query: {
            title: "详情",
            pageId,
            params,
            showHeader: self.$route.query.showHeader,
            pageTitle: title,
            linkTitle: title,
            showBackHeade: true,
            isFromAction: 1,
            _t: Date.now() + ""
        }
    });
}
